import Ember from 'ember';
import DS from 'ember-data';


var selfLinkRegex = new RegExp(".*/([^/]+)/(\\d+).*?$");

export default DS.RESTSerializer.extend({
  serialize: function(snapshot, options) {
    var json = this._super(snapshot, options);
    json.id = snapshot.id;
    return json;
  },
  normalize: function(modelClass, resourceHash, prop) {
    //  console.log(resourceHash);
    //  console.log(prop);
    if ("person" === prop || "people" === prop) {
      resourceHash.roles = resourceHash.roles.map((it) => {
        return {
          id: it.id,
          type: "role"
        };
      });
    }
    return this._super(modelClass, resourceHash, prop);
  },
  //  extractMeta: function(store, typeClass, payload) {
  //    if (payload && !payload.id && payload._embedded && payload.page) {
  //     store.setMetadataFor(typeClass, {total: payload.page.totalElements});
  //   }
  // },
  normalizePayload: function(payload) {
    var afterPayload;
    if (payload._embedded) { // is single object.
      afterPayload = payload._embedded;
    } else {
      var href = payload._links.self.href,
        mt = selfLinkRegex.exec(href),
        ob = {};
      if (!payload.id) {
        payload.id = mt[2];
      }
      // console.log(href);
      // console.log(mt);
      var singular = Ember.Inflector.inflector.singularize(mt[1]);
      ob[singular] = payload; //注意添加
      // console.log(ob);
      return ob;
    }
    // console.log(afterPayload);
    return afterPayload;
  },
  normalizeSaveResponse: function(store, primaryModelClass, payload, id, requestType) {
    return this._super(store, primaryModelClass, payload, id, requestType);
  },
  extractMeta: function(store, modelClass, payload) {
    // console.log(payload && payload.page);
    if (payload && payload.page) {
      store.setMetadataFor(modelClass, {
        total: payload.page.totalElements,
        size: payload.page.size // maybe size is a special property.so change to pageSize;
      }); // sets the metadata for "post"
      delete payload.page; // keeps ember data from trying to parse "total" as a record
    }
  }
});
